package com.cdvtc.flower.web.servlet;

import com.cdvtc.flower.dao.OrderDao;
import com.cdvtc.flower.dao.impl.OrderDaoImpl;
import com.cdvtc.flower.model.CartItem;
import com.cdvtc.flower.model.Customer;
import com.cdvtc.flower.model.Order;
import com.cdvtc.flower.model.Orderdetail;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@WebServlet("/cart-check-out")
public class CheckOutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Customer customer = (Customer) request.getSession().getAttribute("customer");
		if(customer != null) {
			ArrayList<CartItem> cart = (ArrayList<CartItem>) request.getSession().getAttribute("cart");
			if(cart != null) {
				Order order = new Order();
				List<Orderdetail> orderdetailList = new ArrayList<>();
				for (CartItem cartItem : cart) {


					Orderdetail orderdetail = new Orderdetail();
					orderdetail.setProduct(cartItem.getProduct());
					orderdetail.setSale_price(cartItem.getProduct().getSale_price()); // 复制商品价格
					orderdetail.setQuantity(cartItem.getQuantity());

					orderdetailList.add(orderdetail);
				}
				order.setOrderdetailList(orderdetailList);
				order.setCustomer(customer);

				OrderDao oDao = new OrderDaoImpl();
				boolean result = oDao.insertOrder(order);
				if(result) {
					cart.clear();
				}
			}
			response.sendRedirect("orders.jsp");
		}else {
			response.sendRedirect("login.jsp");
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
